package com.iweb.newa202104.service.impl;

import com.iweb.newa202104.Mapper.UserMapper;
import com.iweb.newa202104.dto.UserInputDTO;
import com.iweb.newa202104.dto.UserOutputDTO;
import com.iweb.newa202104.entity.UserEntity;
import com.iweb.newa202104.enums.Err;
import com.iweb.newa202104.exception.CommonException;
import com.iweb.newa202104.service.UserService;
import com.iweb.newa202104.util.CommonUtil;
import com.iweb.newa202104.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;



/**
 * @Author: LGZ
 * @Date: 2021/5/9 22:09
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public ResultVO login(HttpSession session, UserInputDTO userInputDTO) {

        UserOutputDTO userOutputDTO = null;
        UserEntity userEntity;
        try {
            userEntity = userMapper.getUserByPassword(CommonUtil.getMapperFactory().getMapperFacade().map(userInputDTO, UserEntity.class));
        } catch (TransientDataAccessResourceException e) {
            throw new CommonException(Err.PRAM_ERR);
        }

        if (null != userEntity) {
            userOutputDTO = CommonUtil.getMapperFactory().getMapperFacade().map(userEntity, UserOutputDTO.class);
            session.setAttribute("user", userOutputDTO);
            return CommonUtil.ajaxReturn(userOutputDTO);
        } else {
            throw new CommonException(400, "用户名与密码不匹配");
        }

    }

    @Override
    public ResultVO register(UserInputDTO userInputDTO) {
        UserEntity userEntity = CommonUtil.getMapperFactory().getMapperFacade().map(userInputDTO, UserEntity.class);
        try {
            userMapper.insertUser(userEntity);
        } catch (TransientDataAccessResourceException e) {
            throw new CommonException(Err.PRAM_ERR);
        }
        if (userEntity.getUserId() == 0) {
            throw new CommonException(400, "用户名已存在");
        }
        throw new CommonException(Err.SUCCESS);
    }

}
